package org.example.tulurouter.controller;



import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.jsonwebtoken.Claims;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.example.tulurouter.common.BaseContext;
import org.example.tulurouter.common.R;
import org.example.tulurouter.common.exception.DataException;
import org.example.tulurouter.common.exception.ServiceException;
import org.example.tulurouter.domain.User;
import org.example.tulurouter.dto.UserDto;
import org.example.tulurouter.properties.JwtProperties;
import org.example.tulurouter.service.UserService;
import org.example.tulurouter.utils.JwtUtil;
import org.example.tulurouter.vo.UserLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 用户管理
 */
@Slf4j
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserService userService;
    @Value("${OnlineBooks.path}")
    private String basePath;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/register")
    public R<String> register(@RequestBody Map<String,String> formData){
        log.info(" {}  {}  {}",formData);
        User user = new User();
        String username = formData.get("account");
        //判断用户名是否被注册
        List<User> list = userService.list();
        List<String> usernames = list.stream().map(User::getUsername).collect(Collectors.toList());
        if (usernames.contains(username)){
            return R.error("抱歉，该用户名已被注册");
        }
//        String phonenumber = formData.get("phonenumber");
        //判断手机号是否被注册
//        List<String> phonenumbers = list.stream().map(User::getPhoneNumber).collect(Collectors.toList());
//        if (phonenumbers.contains(phonenumber)){
//            return R.error("抱歉，该手机号已被注册");
//        }
        String password = formData.get("password");
        user.setUsername(username);
        user.setPassword(password);
//        user.setPhoneNumber(phonenumber);
        user.setStatus(true);
        user.setRights("user");
        userService.save(user);
        return R.success("注册成功");
    }

    @PostMapping("/login")
    public R<UserLoginVo> login(@RequestBody Map<String,String> formData, HttpSession session){
        log.info("登录{}",formData);
        User user = userService.login(formData);
        //生成JWT令牌
        Map<String,Object> claims= new HashMap<>();
        claims.put("id",user.getUserId());
        String jwt = JwtUtil.createJWT(jwtProperties.getAdminSecretkey(), jwtProperties.getAdminTtl(), claims);
        UserLoginVo userLoginVo  = new UserLoginVo();
        userLoginVo.setUserId(user.getUserId());
        userLoginVo.setUsername(user.getUsername());
//        userLoginVo.setPhoneNumber(user.getPhoneNumber());
        return R.success(userLoginVo);
    }

    /**
     * 返回登录用户信息
     * @return
     */
    @GetMapping("/info")
    public R<UserLoginVo> userinfo(HttpServletRequest request){
        String jwt = request.getHeader("Authorization");
        Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretkey(),jwt);
        Long id = claims.get("id",Long.class);
        LambdaQueryWrapper<User> userlam = new LambdaQueryWrapper<>();
        userlam.eq(User::getUserId,id);
        User user = userService.getOne(userlam);
        UserLoginVo userLoginVo  = new UserLoginVo();
        userLoginVo.setUserId(id);
        userLoginVo.setUsername(user.getUsername());
//        userLoginVo.setPhoneNumber(user.getPhoneNumber());
        return R.success(userLoginVo);
    }

    /**
     * 得到用户登录信息
     * @param request
     * @return
     */
    @GetMapping("/getuserInfo")
    public R<User> getuserInfo(HttpServletRequest request){
        String jwt = request.getHeader("Authorization");
        Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretkey(),jwt);
        Long id = claims.get("id",Long.class);
        LambdaQueryWrapper<User> userlam = new LambdaQueryWrapper<>();
        userlam.eq(User::getUserId,id);
        User user = userService.getOne(userlam);
        return R.success(user);
    }

    /**
     * 修改个人信息
     * @param
     * @return
     */
    @PutMapping("/infoUpdate")
    public R<String> infoUpdate(@RequestBody User user){
        Long id = BaseContext.getCurrentId();
        user.setUserId(id);
        userService.updateById(user);
        return R.success("修改个人信息成功");
    }

    /**
     * 上传头像
     * @param imgUrl
     * @return
     */
    @PostMapping("/uploadAvatar")
    public R<String> uploadAvatar(@RequestParam("imgUrl")MultipartFile imgUrl){
        //初始文件名
        String originalFilename = imgUrl.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //创建一个目录对象
        File dir = new File(basePath);
        //判断当前目录是否存在
        if (!dir.exists()){
            dir.mkdirs();//目录不存在就创建目录
        }
        //使用UUID生成新文件名
        String fileName = UUID.randomUUID() + suffix;
        try{
            //将临时文件转存到指定位置
            imgUrl.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //装填url到user
        userService.setAvatar(basePath + fileName);
        return R.success("上传头像成功！");
    }

    /**
     * 展示头像
     * @param name
     * @param response
     */
    @GetMapping("/getMyavatar")
    public void getMyAvatar(String name, HttpServletResponse response){
        try {
            response.addHeader("Access-Contro1-Allow-Origin","*" );
                    //输入流，通过输入流读取内容
            FileInputStream fileInputStream = new FileInputStream(new File(name));
            response.setContentType("image/jpeg");

                    //输出流，通过输出流将文件写回浏览器，在浏览器里展示图片
            ServletOutputStream outputStream = response.getOutputStream();

            byte[] bytes = new byte[1024];
            int len = 0;
            while( (len = fileInputStream.read(bytes))!= -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }





    /**
     * 点击每一行用户时显示的数据
     * @param userId
     * @return
     */
    @GetMapping("/userDetail")
    public R<User> userDetail(Long userId){
        User user = userService.getById(userId);
        if (user==null){
            throw new DataException("该用户不存在!");
        }
        return R.success(user);
    }

    @PostMapping("/userManageUpdate")
    public R<String> userManageUpdate(@RequestBody User user){
        if (user.getUserId()!=null){
            userService.updateById(user);
        }
        return R.success("修改用户信息成功!");
    }
}
